import {create, deleteById, findOne, list, update} from '@/services/auto-keeper-cluster-api';
import {PlusOutlined} from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable
} from '@ant-design/pro-components';
import {Button, Drawer, message, Modal} from 'antd';
import React, {useRef, useState} from 'react';
import CreateOrUpdateForm from './components/CreateOrUpdateForm';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.AutoKeeperCluster) => {
  const hide = message.loading('正在添加');
  try {
    const res = await create({...fields});
    hide();
    if (res) {
      message.success('添加成功');
      return true;
    }
    return false;
  } catch (error) {
    hide();
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.AutoKeeperCluster) => {
  const hide = message.loading('更新中');
  try {
    const res = await update(fields);
    hide();

    if (res) {
      message.success('更新成功');
      return true;
    }
    return false;
  } catch (error) {
    hide();
    return false;
  }
};


const AutoKeeper: React.FC = () => {

  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [createOrUpdateModalOpen, handleCreateOrUpdateModalOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [isCreate, handleIsCreate] = useState<boolean>(true);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.AutoKeeperCluster>();

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (selectedRows: API.AutoKeeperCluster) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
      const res = await deleteById(selectedRows.id);
      hide();
      if (res) {
        message.success('删除成功');
        actionRef.current?.reload();
        return true;
      }
      return false;
    } catch (error) {
      hide();
      message.error('Delete failed, please try again');
      return false;
    }
  };
  const commonColumns: ProColumns<API.AutoKeeperCluster>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      hideInSearch:true,
    },
    {
      title: '集群名字',
      dataIndex: 'clusterName'
    },
    {
      title: '集群地址',
      dataIndex: ['serverList'],
      renderText: (serverList: any) => serverList?.join(','),
      hideInSearch: true,
    },
    {
      title: '描述',
      dataIndex: ['description'],
      hideInSearch: true,
    }
  ]

  const descriptionColumns: ProColumns<API.AutoKeeperCluster>[] = [
    ...commonColumns,

  ];

  const columns: ProColumns<API.AutoKeeperCluster>[] = [
    ...commonColumns,
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="detail"
          onClick={() => {
            setCurrentRow(record);
            setShowDetail(true);
          }}
        >
          查看
        </a>,
        <a
          key="edit"
          onClick={() => {
            handleCreateOrUpdateModalOpen(true);
            handleIsCreate(false);
            setCurrentRow(record);
          }}
        >
          编辑
        </a>,
        <a
          type='button'
          key="delete"
          onClick={() => {
            Modal.confirm({title: '确实删除?', onOk: () => handleRemove(record)});
          }}
        >删除
        </a>
      ]

    }
  ];

  return (
    <PageContainer>
      <ProTable<API.AutoKeeperCluster, API.PageParams>
        headerTitle='ZooKeeper列表'
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCurrentRow(undefined);
              handleIsCreate(true);
              handleCreateOrUpdateModalOpen(true);
            }}
          >
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={list}
        columns={columns}
      />
      <CreateOrUpdateForm
        onSubmit={async (value) => {
          let success;
          if (currentRow?.id) {
            success = await handleUpdate(value);
          } else {
            success = await handleAdd(value);
          }
          if (success) {
            handleCreateOrUpdateModalOpen(false);
            setCurrentRow(undefined);
            await actionRef?.current?.reload();
          }
        }}
        title={isCreate ? '新建' : '编辑'}
        onCancel={() => {
          handleCreateOrUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalOpen={createOrUpdateModalOpen}
        values={currentRow}
      />

      <Drawer
        width={500}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.id && (
          <ProDescriptions<API.AutoKeeperCluster>
            column={2}
            title={currentRow?.clusterName}
            request={async () => findOne(currentRow?.id)}
            params={{
              id: currentRow?.id,
            }}
            columns={descriptionColumns as ProDescriptionsItemProps<API.AutoKeeperCluster>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default AutoKeeper;
